package com.wgj.android.dialog;

import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ListActivity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.jiaai.xui.jsbridge.CallBackFunction;
import com.wgj.android.R;
import com.wgj.android.custom.addressSelector.AddressSelector;
import com.wgj.android.custom.addressSelector.City;
import com.wgj.android.custom.addressSelector.CityInterface;
import com.wgj.android.custom.addressSelector.OnItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/12/19.
 */

public class AddressSelectDialog extends AppCompatDialogFragment{
    @BindView(R.id.address)
    AddressSelector addressSelector;
    private String province;
    private String cit;
    //全局的jsonObject
    private JSONObject jsonObject;//把全国的省市区的信息以json的格式保存，解析完成后赋值为null
    private String[] allProv;//所有的省
    //省市区的集合
    private Map<String, ArrayList<City>> cityMap = new HashMap<String, ArrayList<City>>();//key:省p---value:市n  value是一个集合
    private Map<String,  ArrayList<City>> areaMap = new HashMap<String,  ArrayList<City>>();//key:市n---value:区s    区也是一个集合

    private CallBackFunction callback;
    private ArrayList<City> cities1 = new ArrayList<>();
    private View view;
    private Dialog dialog;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (view == null){
            super.onCreate(savedInstanceState);
            view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_select_address, null, false);
        }
        ButterKnife.bind(this,view);
        EventBus.getDefault().register(this);
        initJsonData();//初始化json数据
        initDatas();//初始化省市区数据
        initView();
    }
    private void initDatas() {
        try {
            JSONArray jsonArray = jsonObject.getJSONArray("citylist");//获取整个json数据
            allProv = new String[jsonArray.length()];//封装数据
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);//jsonArray转jsonObject
                String provStr = jsonP.getString("p");//获取所有的省
                City city = new City();
                city.setName(provStr);
                cities1.add(city);
                allProv[i] = provStr;//封装所有的省
                JSONArray jsonCity = null;

                try {
                    jsonCity = jsonP.getJSONArray("c");//在所有的省中取出所有的市，转jsonArray
                } catch (Exception e) {
                    continue;
                }
                //所有的市
                ArrayList<City> allCity = new ArrayList<City>();
                for (int c = 0; c < jsonCity.length(); c++) {
                    JSONObject jsonCy = jsonCity.getJSONObject(c);//转jsonObject
                    String cityStr = jsonCy.getString("n");//取出所有的市
                    // allCity[c] = cityStr;//封装市集合
                    City city1 = new City();
                    city1.setName(cityStr);
                    allCity.add(city1);

                    JSONArray jsonArea = null;
                    try {
                        jsonArea = jsonCy.getJSONArray("a");//在从所有的市里面取出所有的区,转jsonArray
                    } catch (Exception e) {
                        continue;
                    }
                    //String[] allArea = new String[jsonArea.length()];//所有的区
                    ArrayList<City> allArea = new ArrayList<City>();
                    for (int a = 0; a < jsonArea.length(); a++) {
                        JSONObject jsonAa = jsonArea.getJSONObject(a);
                        String areaStr = jsonAa.getString("s");//获取所有的区
                        City city2 = new City();
                        city2.setName(areaStr);
                        allArea.add(city2);
                    }
                    areaMap.put(cityStr, allArea);//某个市取出所有的区集合
                }
                cityMap.put(provStr, allCity);//某个省取出所有的市,
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonObject = null;//清空所有的数据
    }
    private void initView() {
        final ArrayList<String> list = new ArrayList<String>();
        list.add("北京");
        list.add("天津");
        list.add("重庆");
        list.add("上海");
        list.add("澳门");
        list.add("香港");
        addressSelector.setTabAmount(3);
        addressSelector.setCities(cities1);
        addressSelector.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void itemClick(AddressSelector addressSelector, CityInterface city, int tabPosition) {
                switch (tabPosition){
                    case 0:
                        ArrayList<City> city1 = cityMap.get(city.getCityName());
                        addressSelector.setCities(city1);
                        province = city.getCityName();
                        break;
                    case 1:
                        addressSelector.setCities(areaMap.get(city.getCityName()));
                        cit =city.getCityName();
                        break;
                    case 2:
                        String str = null;
                        if(!list.contains(province)){
                             str = province+"省-"+cit+"市-"+city.getCityName();
                        }else {
                            str=province+"-"+cit;
                        }

                        if(callback!=null){
                            callback.onCallBack(str);
                        }
                        if(dialog!=null){
                            dialog.dismiss();
                        }
                        break;
                }
            }
        });
        addressSelector.setOnTabSelectedListener(new AddressSelector.OnTabSelectedListener() {
            @Override
            public void onTabSelected(AddressSelector addressSelector, AddressSelector.Tab tab) {

                switch (tab.getIndex()){
                    case 0:

                        addressSelector.setCities(cities1);
                        break;
                    case 1:
                        //province = tab.getText().toString();
                        addressSelector.setCities(cityMap.get(province));
                        break;
                    case 2:
                        // addressSelector.setCities(cities3);
                        break;
                }
            }

            @Override
            public void onTabReselected(AddressSelector addressSelector, AddressSelector.Tab tab) {

            }
        });
    }
    public void setCallBackFunction(CallBackFunction callback){
        this.callback=callback;
    }

    private void initJsonData() {
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = getActivity().getAssets().open("city.json");//打开json数据
            byte[] by = new byte[is.available()];//转字节
            int len = -1;
            while ((len = is.read(by)) != -1) {
                sb.append(new String(by, 0, len, "utf-8"));//根据字节长度设置编码
            }
            is.close();//关闭流
            jsonObject = new JSONObject(sb.toString());//为json赋值
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onCallBank(CallBackFunction callBackFunction){
        callback =callBackFunction;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
         super.onCreateDialog(savedInstanceState);
        if(dialog==null){
            // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。
            initDialogStyle(view);
        }
        return dialog;
    }
    private void initDialogStyle(View view) {
        dialog = new Dialog(getActivity(), R.style.dialog_setting);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.popupwindow_anim_style);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width =WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
